package com.leetcode.leetcode2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 串联所有单词的子串
 *
 * @author luhd
 * @date 2022-01-07
 */
public class Practice30 {
    /**
     * 给定一个字符串 s 和一些 长度相同 的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
     */
    public static void main(String[] args) {
        String s = "barfoothefoobarman";
        String[] words = {"foo","bar"};
        List<Integer> substring = findSubstring(s, words);
        System.out.println(substring);
    }
    public static List<Integer> findSubstring(String s, String[] words) {
        List<Integer> res = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
        int word_num = words.length;
        int one_word = words[0].length();
        int all_len = word_num * one_word;
        if(s==null ||s.length()==0 ||word_num==0||words==null) {
            return res;
        }
        for(String word: words) {
            map.put(word,map.getOrDefault(word,0)+1);
        }
        for (int i = 0; i < s.length()-all_len+1; i++) {
            // 截取字符串s的长度和，数组拼接的长度一致
            String temp = s.substring(i,i+all_len);
            HashMap<String, Integer> tmp_map = new HashMap<>();
            for (int j = 0; j < all_len; j+=one_word) {
                String w = temp.substring(j,j+one_word);
                tmp_map.put(w,tmp_map.getOrDefault(w,0)+1);
            }
            if (map.equals(tmp_map)) {
                res.add(i);
            }
        }
        return res;
    }
}
